<template>
  <view class="body">
    <view class="date_top">
      <view class="date_btn" @tap="showCalendar">
        <text class="date">{{ isToday(state.today) }}</text>
        <image
          class="img_arrow"
          v-if="!state.datepickShow"
          src="https://ainengli.meilianshuke.com/jkhx/common/arrow_down.png"
        />
        <image
          class="img_arrow"
          v-if="state.datepickShow"
          src="https://ainengli.meilianshuke.com/jkhx/common/arrow_up.png"
        />
      </view>
    </view>
    <up-popup :show="state.dateShow" :round="16" mode="bottom" @close="closeCalendar">
      <uni-calendar
        :date="parseTime(state.today, '{y}-{m}-{d}')"
        :showMonth="false"
        :selected="state.hasData"
        @change="setDate"
        @monthSwitch="getMouthDate"
      />
      <!-- :selected="state.dateSelects" -->
    </up-popup>

    <view class="seven">
      <view
        v-for="(item, index) in state.weekList"
        :key="index"
        :class="['items', index == state.active ? 'active' : '']"
        @tap="selectDate(item, index)"
        >{{ WEEK[item - 1] }}</view
      >
    </view>
    <view v-if="state.dateSelects.length == 0" class="nodata">
      <image class="img_nodata" src="https://ainengli.meilianshuke.com/jkhx/noData.png" />
      <view class="nodata_text">还没有记录</view>
      <view class="nodata_text">请点击屏幕下方按钮来添加</view>
    </view>
    <view class="today_sport" v-else>
      <up-swipe-action ref="swipeRef" autoClose>
        <up-swipe-action-item
          v-for="(item, index) in state.dateSelects"
          :key="index"
          :options="options"
          @click="handleClick(item)"
        >
          <view class="sport-item">
            <view class="sport-item-left">
              <text class="title">{{ item.sportName }}</text>
              <text class="desc">{{ item.duration || '--' }}分钟 {{ item.consume }}千卡</text>
            </view>
            <view v-if="item.source == '手动录入'" class="sport-item-right" @tap="toDetail(item)">
              <text>查看</text>
              <img
                class="img"
                src="https://ainengli.meilianshuke.com/jkhx/raozg/green_more.png"
                alt=""
              />
            </view>
            <view v-if="item.source == '华为运动健康'" class="sport-item-right-huawei">
              <img
                class="img"
                src="https://ainengli.meilianshuke.com/jkhx/common/huawei-logo.png"
                alt=""
              />
              <text>来自华为运动健康</text>
            </view>
            <view v-if="item.source == '运动方案'" class="sport-item-right-scheme">
              <img
                class="img"
                src="https://ainengli.meilianshuke.com/jkhx/common/scheme-logo.png"
                alt=""
              />
              <text>来自运动方案</text>
            </view>
          </view>
        </up-swipe-action-item>
      </up-swipe-action>
    </view>
    <view class="fixed" @tap="recordSports">
      <button class="fix-btn">记运动</button>
    </view>
    <up-modal
      :show="show"
      :title="'提示'"
      :closeOnClickOverlay="true"
      :showCancelButton="true"
      :confirmColor="'#FF503D'"
      @confirm="deleteSports"
      @close="cancel"
      @cancel="cancel"
    >
      <view
        style="width: 100%; text-align: center; color: #4e5969; font-size: 30rpx; font-weight: 400"
        >确认要删除该运动?</view
      >
    </up-modal>

    <!-- 运动设置 -->
    <up-popup :show="state.setShow" :round="16" mode="bottom" closeable @close="close">
      <view class="food_info">
        <view class="title"> 运动信息 </view>
        <view class="info_top">
          <view class="name">{{ state.addSport.sportName }}</view>
        </view>
        <view class="input_info">
          <input
            type="digit"
            class="weight_input"
            :focus="state.tipFocus"
            :maxlength="4"
            @input="onInput"
            :adjustPosition="false"
            @keyboardheightchange="onKey"
            v-model="state.addSport.minutes"
          />
          <view class="unit">分钟</view>
          <view class="hot">(根据您的体重计算，消耗约{{ state.addSport.energy || '--' }}千卡)</view>
        </view>
        <button class="submit" @tap="sportSelect">确定</button>
        <view class="bottom_box" :style="{ height: `${state.bottomHeight}rpx` }" />
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { throttle, debounce, parseTime } from '@/utils/tools'
import { formatDate } from '@/utils/util'
import { onLoad, onShow } from '@dcloudio/uni-app'
import {
  getSportRecord,
  getSportsInfoByDate,
  calculateEnergy,
  saveSportRecord,
  del_sports
} from './sportsInfo.api'

const WEEK = ['一', '二', '三', '四', '五', '六', '日']

const state = reactive({
  now: new Date(),
  yearsAgo: new Date().setFullYear(new Date().getFullYear() - 1),
  today: new Date(),
  datepickShow: false,
  dateShow: false,
  dateSelects: [],
  hasData: [],
  show: false,
  setShow: false,
  addSport: {},
  userInfo: {},
  active: 0,
  weekList: [],
  tipFocus: false,
  bottomHeight: 0
})
const options = reactive([
  {
    text: '删除',
    style: {
      backgroundColor: '#ff503d'
    }
  }
])
const swipeRef = ref()
const hasFinishCalculate = ref(true)
const show = ref(false)
const delSport = reactive({
  id: ''
})

onLoad((option) => {
  state.today = option && option.today ? new Date(option.today) : new Date()
})

onShow(() => {
  state.userInfo = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  state.show = false
  getTime()
  getData()
  const currentMouth = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1
  }
  getMouthDate(currentMouth)
})
watch(
  () => state.addSport.minutes,
  (n) => {
    hasFinishCalculate.value = false
  },
  {
    immediate: true
  }
)

const showCalendar = () => {
  state.datepickShow = !state.datepickShow
  state.dateShow = !state.dateShow
}
const closeCalendar = () => {
  state.dateShow = false
  state.datepickShow = false
}

const getData = () => {
  const params = {
    empi: state.userInfo.empi,
    date: parseTime(state.today, '{y}-{m}-{d}'),
    sportTypes: '1,2'
  }

  getSportRecord(params).then((res: any) => {
    state.dateSelects = res.data
  })
}
const getMouthDate = (e) => {
  e.month = Number(e.month)
  const mouthStart =
    (e.month == 1 ? e.year - 1 : e.year) + '/' + (e.month == 1 ? 12 : e.month - 1) + '/20'
  const mouthEnd =
    (e.month == 12 ? e.year + 1 : e.year) + '/' + (e.month == 12 ? 1 : e.month + 1) + '/15'
  const params = {
    empi: state.userInfo.empi,
    startDate: formatDate(new Date(mouthStart), 'yyyy-MM-dd'),
    endDate: formatDate(new Date(mouthEnd), 'yyyy-MM-dd'),
    sportTypes: '1,2'
  }
  getSportsInfoByDate(params).then((res) => {
    if (res.data && res.data.length > 0) {
      res.data.forEach((item) => {
        item.date = item.takeTime.split(' ')[0]
        item.info = ''
      })
      state.hasData = res.data
    }
  })
}

const getTime = () => {
  const day = state.today.getDay()
  state.weekList = [1, 2, 3, 4, 5, 6, 7]
  state.weekList.forEach((item, index) => {
    if (day === 0) {
      state.active = 6
    }
    if (day == item) {
      state.active = index
    }
  })
}
const isToday = (val) => {
  // 今天昨天前天转换
  const select = parseTime(val, 'yyyy/MM/dd') + ' 00:00:00'
  const today = parseTime(state.now, 'yyyy/MM/dd') + ' 00:00:00'
  if (new Date(today).getTime() - new Date(select).getTime() == 0) {
    return '今天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 86400000) {
    return '昨天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 172800000) {
    return '前天'
  } else {
    return parseTime(val, '{y}-{m}-{d}')
  }
}
const setDate = (e) => {
  state.datepickShow = false
  state.dateShow = false
  state.today = new Date(e.fulldate)
  console.log(state.today, e.fulldate)
  getTime()
  getData()
}
const selectDate = (data: any, index: number) => {
  let sub = 0
  const currentDay = state.today.getDay() // 当前是周几（0 表示周日）
  if (currentDay === 0) {
    sub = data - 7
  } else {
    sub = data - currentDay
  }
  let selectWeek = new Date(state.today.getTime() + sub * 86400000)
  state.active = index
  state.today = selectWeek
  getData()
}

const toDetail = async (val: any) => {
  state.addSport = val
  state.addSport.minutes = val.duration
  state.setShow = true
  await getcalculateEnergy()
  setTimeout(() => {
    // 解决弹窗打开时，input无法获取焦点问题
    state.tipFocus = true
  }, 100)
}

const onKey = (e) => {
  const sys = uni.getSystemInfoSync()
  // 自定义弹出键盘事件
  if (e.detail.height) {
    state.bottomHeight = e.detail.height * 2 - sys.safeAreaInsets.bottom * 2 - 36
  } else {
    state.bottomHeight = 0
  }
}
const onInput = debounce(async (e) => {
  if (e.detail.value * 1 > 3000) {
    state.addSport.minutes = 3000
  }
  if (!state.addSport.minutes || isNaN(state.addSport.minutes)) {
    state.addSport.energy = 0
  } else {
    await getcalculateEnergy()
  }
}, 200)

// 计算能量
const getcalculateEnergy = () => {
  calculateEnergy({
    sportId: state.addSport.sportId,
    empi: state.userInfo.empi,
    actionType: state.addSport.actionType,
    sex: state.userInfo.gender == '男性' ? 1 : 2,
    minutes: Number(state.addSport.minutes)
  }).then((res) => {
    state.addSport.energy = res.data.energyValue
    hasFinishCalculate.value = true
  })
}

const handleClick = (item: any) => {
  if (item.source == '运动方案') {
    uni.showToast({
      title: '该数据由运动方案同步，不支持删除!',
      icon: 'none'
    })
    swipeRef.value.closeAll()
    return
  }
  if (item.source == '华为运动健康') {
    uni.showToast({
      title: '该数据由华为运动健康同步，不支持删除!',
      icon: 'none'
    })
    swipeRef.value.closeAll()
    return
  }
  delSport.id = item.id
  show.value = true
}
const cancel = () => {
  show.value = false
  swipeRef.value.closeAll()
}
const deleteSports = () => {
  uni.showLoading()
  del_sports({ id: delSport.id })
    .then((res) => {
      uni.hideLoading()
      show.value = false
      getData()
      swipeRef.value.closeAll()
      uni.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 2000
      })
    })
    .catch((err) => {
      console.log(err)
      show.value = false
    })
}

const close = () => {
  state.setShow = false
  state.tipFocus = false
  state.bottomHeight = 0
}

const sportSelect = throttle(() => {
  if (!state.addSport.minutes || state.addSport.minutes == '0' || isNaN(state.addSport.minutes)) {
    uni.showToast({
      title: '请输入正确时间!',
      icon: 'error'
    })
    return
  }
  if (hasFinishCalculate.value) {
    const data = [
      {
        id: state.addSport.id,
        takeTime: state.addSport.takeTime,
        sportId: state.addSport.sportId,
        sportName: state.addSport.sportName,
        sportType: state.addSport.sportType,
        consume: state.addSport.energy,
        empi: state.addSport.empi,
        duration: state.addSport.minutes
      }
    ]
    saveSportRecord(data).then((res) => {
      state.setShow = false
      state.tipFocus = false
      getData()
    })
  } else {
    uni.showToast({
      title: '请等待运动消耗计算完毕',
      icon: 'none'
    })
  }
}, 300)
const recordSports = (val: string) => {
  uni.navigateTo({
    url:
      '/module/src/pages/sports/sportsInfo/detail?food=' +
      val +
      '&date=' +
      parseTime(state.today, '{y}-{m}-{d}')
  })
  // uni.navigateTo({
  //   url: '/module/src/pages/sports/sportsQuestionnaire/feedbackResult?type=todayFeedback'
  // })
  // uni.navigateTo({
  //   url: `/module/src/pages/sports/sportsQuestionnaire/feedback`
  // })
}
</script>

<style lang="scss" scoped>
.body {
  height: 100vh;
  padding: 0 32rpx;
  padding-bottom: calc(156rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(156rpx + env(safe-area-inset-bottom));

  .date_top {
    text-align: center;

    .date_btn {
      box-sizing: border-box;
      display: inline-block;
      height: 60rpx;
      padding: 0 32rpx;
      margin: 24rpx auto;
      line-height: 60rpx;
      text-align: center;
      background: #fff;
      border-radius: 38rpx;

      .date {
        font-size: 28rpx;
        font-weight: 400;
        color: #222;
      }

      .img_arrow {
        width: 24rpx;
        height: 24rpx;
        margin-left: 16rpx;
      }
    }
  }

  .seven {
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    margin-bottom: 26rpx;

    .items {
      box-sizing: border-box;
      width: 77rpx;
      height: 76rpx;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 76rpx;
      color: #222;
      text-align: center;
      background: #fff;
      border-radius: 12rpx;
    }

    .active {
      color: #fff;
      background: #00d1b6;
    }
  }

  .today_sport {
    position: relative;
    box-sizing: border-box;
    height: calc(100vh - 400rpx);
    overflow: hidden auto;
    ::v-deep .u-swipe-action-item {
      border-radius: 12rpx !important;
      margin-bottom: 24rpx !important;
    }
    ::v-deep .u-swipe-action-item__right__button__wrapper {
      border-radius: 0 12rpx 12rpx 0 !important;
      font-weight: 400;
      font-size: 24rpx;
      color: #ffffff;
    }
    .sport-item {
      width: 100%;
      padding: 32rpx;
      background-color: #fff;
      border-radius: 16rpx;
      // margin-bottom: 24rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-direction: row;
      position: relative;

      .sport-item-left {
        display: flex;
        flex-direction: column;
        .title {
          font-weight: 500;
          font-size: 30rpx;
          color: #333333;
          margin-bottom: 10rpx;
        }

        .desc {
          font-weight: 400;
          font-size: 28rpx;
          color: #999999;
        }
      }

      .sport-item-right {
        padding: 0 24rpx;
        font-weight: 500;
        font-size: 28rpx;
        color: #00d1b6;
        border-radius: 28rpx;
        border: 1rpx solid #00d1b6;
        transform: rotateZ(360deg);
        height: 56rpx;
        line-height: 56rpx;
        .img {
          width: 32rpx;
          height: 32rpx;
          transform: translateY(6rpx);
        }
      }
      .sport-item-right-huawei,
      .sport-item-right-scheme {
        position: absolute;
        top: 32rpx;
        right: 32rpx;
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
        .img {
          width: 32rpx;
          height: 32rpx;
          transform: translateY(4rpx);
          margin-right: 8rpx;
        }
      }
      .sport-item-right-scheme .img {
        transform: translateY(8rpx);
      }
    }
  }

  .nodata {
    text-align: center;

    .img_nodata {
      width: 320rpx;
      height: 240rpx;
      margin-top: 60rpx;
    }

    .nodata_text {
      font-size: 28rpx;
      font-weight: 400;
      color: #666;
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    // gap: 24rpx;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;

    .fix-btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 700;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;
    }
  }

  ::v-deep .u-popup {
    // 设置重量弹窗
    .food_info {
      padding: 0 32rpx;

      .title {
        width: 100%;
        height: 104rpx;
        font-size: 30rpx;
        font-weight: 500;
        line-height: 104rpx;
        color: #333;
        text-align: center;
      }

      .info_top {
        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #222;
        }

        .power {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }
      }

      .info_detail {
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        padding: 20rpx 0;
        margin: 26rpx 0 30rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #999;
        border-top: 1rpx solid #e5e6eb;
        border-bottom: 1rpx solid #e5e6eb;

        .detail_item {
          flex: 1;
          text-align: center;

          .text {
            margin-bottom: 10rpx;
          }
        }
      }

      .input_info {
        position: relative;
        text-align: center;

        .weight_input {
          width: 200rpx;
          height: 84rpx;
          margin: 0 auto;
          font-size: 60rpx;
          font-weight: 500;
          color: #1cd7ae;
          border-bottom: 4rpx solid #1cd7ae;
        }

        .unit {
          position: absolute;
          top: 0;
          right: 235rpx;
          font-size: 24rpx;
          font-weight: 500;
          color: #1cd7ae;
        }

        .hot {
          margin-top: 16rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #666;
        }
      }

      .submit {
        width: 100%;
        height: 88rpx;
        padding: 0 !important;
        margin: 76rpx 0 32rpx;
        font-size: 32rpx !important;
        font-weight: 500;
        line-height: 88rpx !important;
        color: #fff;
        background: #00d1b6;
        border-radius: 50rpx;
      }
    }
    .u-popup__content {
      overflow: hidden;

      .uni-calendar {
        .uni-calendar__header {
          .uni-calendar__header-text {
            font-size: 30rpx !important;
          }
        }

        .uni-calendar__box {
          .uni-calendar__weeks-day-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item__weeks-box-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item--isDay {
            border-radius: 8rpx;
          }
        }
      }
    }
  }

  ::v-deep .dialog-close {
    display: none;
  }

  ::v-deep .uni-calendar-item--isDay {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item--checked {
    background: #00d1b6;
  }

  ::v-deep .uni-date-editor {
    width: 254rpx;
    margin: 0 auto;
  }

  ::v-deep .uni-calendar-item--isDay-text {
    color: #00d1b6;
  }

  ::v-deep .uni-calendar-item--isDay .uni-calendar-item--isDay-text {
    color: #fff;
  }

  ::v-deep .uni-calendar-item__weeks-box-circle {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item__weeks-box .uni-calendar-item--checked {
    background-color: #00d1b6;
  }

  ::v-deep .uni-calendar__weeks-day {
    background: #ebfbf9;

    .uni-calendar__weeks-day-text {
      color: #00d1b6;
    }
  }

  ::v-deep .uni-datetime-picker--btn {
    height: 88rpx;
    line-height: 88rpx;
    background-color: #00d1b6;
  }

  ::v-deep .uni-progress-bar,
  ::v-deep .uni-progress-inner-bar {
    border-radius: 100rpx;
  }

  ::v-deep .u-icon__icon {
    top: 16rpx !important;
    font-size: 40rpx !important;
  }
}
</style>
